﻿namespace gRPCDemo.Dbservice
{
    public class Client:BLL.IDbServiceClient
    {
        //调Dbservice的Grpc接口发数据到OPC
        public async Task GrpcTest()
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);
            var channel = GrpcChannel.ForAddress("http://localhost:5555");
            var module = new Module.ModuleClient(channel);
            var request = new ModelResult
            {
                TaskId = "3ceafda8-65db-4f47-88b2-2601d6bb3c3e",
                Time = "2023-7-13 13:14:00",
                Content = "温度",
                Level = 2,
                Message = "成功",
            };
            request.Value.Add(new Basis
            {
                Name = "传感器值",
                Show = 1,
                Type = "PLAIN:Number",
                Value = Google.Protobuf.ByteString.CopyFromUtf8("60")
            });
            request.Value.Add(new Basis
            {
                Name = "位置",
                Show = 1,
                Type = "PLAIN:String",
                Value = Google.Protobuf.ByteString.CopyFromUtf8("20m")
            });
            await module.write_resultAsync(request);


            request = new ModelResult
            {
                TaskId = "3ceafda8-65db-4f47-88b2-2601d6bb3c3e",
                Time = "2023-7-28 13:14:00",
                Content = "声音",
                Level = 2,
                Message = "成功",
            };
            request.Value.Add(new Basis
            {
                Name = "传感器值",
                Show = 1,
                Type = "PLAIN:Number",
                Value = Google.Protobuf.ByteString.CopyFromUtf8("120")
            });
            request.Value.Add(new Basis
            {
                Name = "位置",
                Show = 1,
                Type = "PLAIN:String",
                Value = Google.Protobuf.ByteString.CopyFromUtf8("50m")
            });
            await module.write_resultAsync(request);

            var request2 = new ModelStatus
            {
                EquipmentId = "0a532222-6621-4031-9dd5-d8495cb1b04b",
                Name = "电量",
                Value = "50",
                Time = "2023-6-1 13:14:00"
            };
            await module.update_statusAsync(request2);


            request2 = new ModelStatus
            {
                EquipmentId = "0a532222-6621-4031-9dd5-d8495cb1b04b",
                Name = "模组正常",
                Value = "false",
                Time = "2023-6-1 13:14:00"
            };
            await module.update_statusAsync(request2);


            request2 = new ModelStatus
            {
                EquipmentId = "0a532222-6621-4031-9dd5-d8495cb1b04b",
                Name = "通讯正常",
                Value = "true",
                Time = "2023-6-1 13:14:00"
            };
            await module.update_statusAsync(request2);


            request2 = new ModelStatus
            {
                EquipmentId = "0a532222-6621-4031-9dd5-d8495cb1b04b",
                Name = "状态",
                Value = "不正常",
                Time = "2023-6-1 13:14:00"
            };
            await module.update_statusAsync(request2);


            request2 = new ModelStatus
            {
                EquipmentId = "0a532222-6621-4031-9dd5-d8495cb1b04b",
                Name = "室温",
                Value = "300",
                Time = "2023-6-1 13:14:00"
            };
            await module.update_statusAsync(request2);


            Console.WriteLine("数据初始化完成");
            var input = "0";
            while (!string.IsNullOrWhiteSpace(input))
            {
                if (int.TryParse(input, out int val))
                {
                    var request3 = new ModelStatus
                    {
                        EquipmentId = "0a532222-6621-4031-9dd5-d8495cb1b04b",
                        Name = "电量",
                        Value = val.ToString(),
                        Time = "2023-6-1 13:14:00"
                    };
                    await module.update_statusAsync(request3);
                }
                Console.WriteLine("输入电量值，整数，直接回车退出！");
                input = Console.ReadLine();
            }
        }

        public async Task ZSGrpcTest()
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);
            await Console.Out.WriteLineAsync("grpc端口：");
            var port = Console.ReadLine();
            string url = $"http://localhost:{port}";
            var channel = GrpcChannel.ForAddress(url);
            var module = new Module.ModuleClient(channel);

            //发送开始任务
            var json = File.ReadAllText("zs.json");
            var jdoc = JsonDocument.Parse(json);
            var taskEl = jdoc.RootElement.GetProperty("taskStart");

            var request0 = new ModelTaskStart
            {
                Id = Guid.NewGuid().ToString(),
                JobId = taskEl.GetProperty("jobId").GetString(),
                Operator = "操作人测试",
                StartMode = "启动模式测试",
                StartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            };
            await module.task_startAsync(request0);
            do
            {
                //发送结果
                json = File.ReadAllText("zs.json");
                jdoc = JsonDocument.Parse(json);
                var resultEl = jdoc.RootElement.GetProperty("result");

                var request1 = new ModelResult
                {
                    TaskId = request0.Id,
                    Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Content = resultEl.GetProperty("content").GetString(),
                    Level = resultEl.GetProperty("level").GetInt32(),
                    Message = resultEl.GetProperty("message").GetString(),
                };
                var basisEnumerate = resultEl.GetProperty("basis").EnumerateArray();
                while (basisEnumerate.MoveNext())
                {
                    var type = basisEnumerate.Current.GetProperty("type").GetString();
                    Google.Protobuf.ByteString val;
                    if (type == "MIME:image/jpeg")
                    {
                        val = Google.Protobuf.ByteString.CopyFrom(File.ReadAllBytes(basisEnumerate.Current.GetProperty("value").GetString()));
                    }
                    else
                    {
                        val = Google.Protobuf.ByteString.CopyFromUtf8(basisEnumerate.Current.GetProperty("value").GetString());
                    }
                    request1.Value.Add(new Basis
                    {
                        Name = basisEnumerate.Current.GetProperty("name").GetString(),
                        Show = basisEnumerate.Current.GetProperty("show").GetInt32(),
                        Type = type,
                        Value = val
                    });
                }
                await module.write_resultAsync(request1);

                Console.WriteLine("空格再次发送结果，回车进入状态发送！");
            } while (Console.ReadKey().Key != ConsoleKey.Enter);

            Console.WriteLine("数据初始化完成");
            //发送状态
            do
            {
                json = File.ReadAllText("zs.json");
                jdoc = JsonDocument.Parse(json);

                var statustEl = jdoc.RootElement.GetProperty("status");
                var statusEnumerate = statustEl.EnumerateArray();
                while (statusEnumerate.MoveNext())
                {
                    var request2 = new ModelStatus
                    {
                        EquipmentId = statusEnumerate.Current.GetProperty("equipmentId").GetString(),
                        Name = statusEnumerate.Current.GetProperty("name").GetString(),
                        Value = statusEnumerate.Current.GetProperty("value").GetString(),
                        Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                    };
                    await module.update_statusAsync(request2);
                }

                Console.WriteLine("空格继续，回车退出！");
            } while (Console.ReadKey().Key != ConsoleKey.Enter);
        }
    }
}
